package demo1;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import domain.Address;
import domain.Student;
import domain.Userinfo;
import mappers.StudentMapper;
import mappers.UserinfoMapper;

public class demo1 {

	public static void main(String[] args) throws Exception {
		 
		// 1.创建链接
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		// 2.打开链接
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// 3.ִ执行sql语句
		/*
		 * StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
		 * List<Student> list = studentMapper.selectStudent();
		 */
		UserinfoMapper userinfoMapper = sqlSession.getMapper(UserinfoMapper.class);
		List<Userinfo> userinfos= userinfoMapper.selectUserinfo(1);
		// 4.输出结果
		
		/*
		 * for (Student student : list) { System.out.println("stuId:" +
		 * student.getStuId() + "|stuName:" + student.getStuName() + "|createTime:" +
		 * student.getCreateTime() + "|createDate" + student.getCreateDate()); }
		 */
		 
		
		
		  for(Userinfo userinfo : userinfos) {
		  System.out.println("Userinfo:"+userinfo.getUserId()+"|"+userinfo.getUserName(
		  )+"|"+userinfo.getPassword());
		  System.out.println("Address:"+userinfo.getAddress().getAddrId()+"|"+userinfo.
		  getAddress().getCity()); }
		 
		 
		// 5.关闭链接
		  sqlSession.commit();
		sqlSession.close();

	}
	
	private static SqlSessionFactory getSqlSessionFactory() {
		SqlSessionFactory sessionFactory=null;
		String driver="com.mysql.jdbc.Driver";
	    String url="jdbc:mysql://localhost:3307/demo1?useSSL=false&&allowPublicKeyRetrieval=true";
		String username="root";
		String password="jiangsongdong";
		PooledDataSource pooledDataSource = new PooledDataSource(driver,url,username,password);
		JdbcTransactionFactory jdbcTransactionFactory=new JdbcTransactionFactory();
		Environment environment = new Environment("development", jdbcTransactionFactory, pooledDataSource);
		Configuration configuration = new Configuration(environment);
		configuration.getTypeAliasRegistry().registerAlias("student",Student.class);
		configuration.addMapper(StudentMapper.class);
		configuration.addMapper(UserinfoMapper.class);
		sessionFactory = new SqlSessionFactoryBuilder().build(configuration);
		return sessionFactory;
		
	}

}
